#include "degfx/bitmap.h"
#include <assert.h>

void mx_bitmap_blitstretch(const MX_BITMAP * src, MX_BITMAP * dest, int sx, int sy, int sw, int sh, int dx, int dy, int dw, int dh)
{
	int x, y;
	MX_BITMAP_ITER srci, dsti;

	assert(src != dest);

	/** The default source poisition is 0,0. */
	if (sx == MXDEFAULT)
		sx = 0;
	if (sy == MXDEFAULT)
		sy = 0;

	/** The default source height and width is the height and width of the source bitmap. */
	if (sw == MXDEFAULT)
		sw = mx_w(src);
	if (sh == MXDEFAULT)
		sh = mx_h(src);

	/** The default destination poisition is 0,0. */
	if (dx == MXDEFAULT)
		dx = 0;
	if (dy == MXDEFAULT)
		dy = 0;

	/** The default destinantion height and width is the height and width of the destination bitmap. */
	if (dw == MXDEFAULT)
		dw = sw;
	if (dh == MXDEFAULT)
		dh = sh;

	if ((dw == sw) && (dh == sh)) {
		mx_bitmap_blit(src, dest, sx, sy, dx, dy, dw, dh);
		return;
	}

	if (dy + dh < dest->_clip.y1)
		return;

	if (dx + dw < dest->_clip.x1)
		return;

	++sw;
	++sh;
	++dw;
	++dh;

/**todo Bitmap stretch algorithm is very simple and could definetly be improved. */
	for (y = 0; y < dh; y++) {
		const int ddy = dy + y;

		if (ddy > dest->_clip.y2)
			y = dh;

		else if (ddy >= dest->_clip.y1) {
			dsti = mx_bitmap_iter(dest, dest->_clip.x1, ddy);
			srci = mx_bitmap_iter(src, sx, sy + (y * sh) / dh);

			dsti += dx - dest->_clip.x1;

			for (x = 0; x < dw; x++) {
				const int ddx = dx + x;

				if (ddx > dest->_clip.x2)
					x = dw;

				else if (ddx >= dest->_clip.x1)
					*dsti = MXBLEND(srci[(x * sw) / dw], *dsti);

				++dsti;
			}
		}
	}
}
